package com.mjk.common.tools.plumelog.service.config;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.plumelog.service.InitConfig;
import com.mjk.common.tools.plumelog.service.controller.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.Objects;

public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        if (!Objects.equals(request.getMethod(), HttpMethod.POST.name())) {
//            return true;
//        }
//        if (StringUtils.isEmpty(InitConfig.loginUsername))
//            return true;
//        Object token = request.getSession().getAttribute("token");
//        if (token == null) {
//            printMessage(response);
//            return false;
//        }
        return StpUtil.isLogin();
    }


    private void printMessage(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSON.toJSONString(Result.UN_LOGIN));
        } catch (Exception e) {
            BizLogger.error(e);
        }
    }

}
